<?php

/**
 * emailCampaigns actions.
 *
 * @package    ecrm
 * @subpackage emailCampaigns
 * @author     Saul Santiago
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class emailCampaignsActions extends sfActions
{
 /**
  * Executes index action
  *
  * @param sfRequest $request A request object
  */
  public function executeIndex(sfWebRequest $request)
  {
    $this->tableColumns = EmailCampaignsTable::TableColumns();
  }
  
  public function executeAjaxdata(sfWebRequest $request) 
  {
    sfConfig::set('sf_web_debug', false);
    $this->getResponse()->setContentType('application/json');
    $this->databases = Doctrine::getTable('EmailCampaigns');
    $json = $this->databases->fetchData($request);
    return $this->renderText($json);
  }
  
  public function executeAjaxNewForm(sfWebRequest $request) 
  {
    sfConfig::set('sf_web_debug', false);
    $form = new EmailCampaignsForm();
    return $this->renderPartial("emailCampaignsForm", array("form"=>$form));
  }
  
  public function executeAjaxEditForm(sfWebRequest $request) 
  {
    $data = Doctrine_Core::getTable('EmailCampaigns')->findOneById($request->getParameter('id'));
    $form = new EmailCampaignsForm($data);
    return $this->renderPartial("emailCampaignsForm", array("form" => $form));
  }  
  
  public function executeAjaxSave(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST));
    sfConfig::set('sf_web_debug', false);
    $this->getResponse()->setContentType('application/json');
    $this->form = new EmailCampaignsForm();
    $data_array = $this->processForm($request, $this->form);
    return $this->renderText(json_encode($data_array));
  }   
  
  private function processForm(sfWebRequest $request, sfForm $form)
  {
    $form->bind($request->getParameter($form->getName()));

    $boolIsNew = ($form->getObject()->isNew() ? true : false );

    if ($form->isValid()) {
      try {
        $application = $form->save();

        $data_arr = array("valid" => 'true', "message" => 'Data successfully saved!', "id" => $application->getId());
      }
      catch (Exception $exc) {
        $data_arr = array("valid" => 'false', "message" => $exc->getMessage());
      }
    }
    else {
      $errors = $form->getErrorSchema()->getErrors();
      $errorText = '';
      foreach($errors as $key=>$val) {
        $errorText .= $key.': '.$val.'|';
      }
      $data_arr = array("valid" => 'false', "message" => $errorText);
    }
    return $data_arr;
  }
  
  public function executeUpdate(sfWebRequest $request) 
  {
    $this->forward404unless($request->isXmlHttpRequest());
    $formValues = $request->getParameter('email_campaigns');
    $this->forward404Unless($application = Doctrine_Core::getTable('EmailCampaigns')->find(array($formValues['id']))  , sprintf('Object EmailCampaigns does not exist (%s).', array($formValues['id'])));
    $this->getResponse()->setContentType('application/json');
    $this->form = new EmailCampaignsForm($application);
    $data_array = $this->processForm($request, $this->form);
    return $this->renderText(json_encode($data_array));
  }    
  
  public function executeDelete(sfWebRequest $request) 
  {
    $this->forward404unless($request->isXmlHttpRequest());
    sfConfig::set('sf_web_debug', false);
    $this->getResponse()->setContentType('application/json');
    $this->forward404Unless($application = Doctrine_Core::getTable('EmailCampaigns')->find(array($request->getParameter('id'))), sprintf('Object EmailCampaigns does not exist (%s).', $request->getParameter('id')));
    try {
      $application->delete();
      $data_arr = array("valid" => 'true', "message" => 'Data was successfully deleted!');
    }
    catch (Exception $exc) {
      $data_arr = array("valid" => 'false', "message" => $exc->getMessage());
    }
    return $this->renderText(json_encode($data_arr));
  }

  public function executeView(sfWebRequest $request)
  {
    sfConfig::set('sf_web_debug', false);
    $this->forward404Unless($emailCampaignId = $request->getParameter('id'));
    $emailCampaign = Doctrine_Core::getTable('EmailCampaigns')->find($emailCampaignId, Doctrine_Core::HYDRATE_ARRAY);
    $emailCampaignPerformance = EmailCampaignUserPerformanceTable::getStats($emailCampaignId);
    return $this->renderPartial('infos',array('campaign'=>$emailCampaign, 'campaignPerformance'=>$emailCampaignPerformance));   
  }
  
  public function executeReport(sfWebRequest $request)
  {
    // header('Content-Type: text/plain');
    // header('Content-Disposition: attachment;filename="ApplicationReport.xls"');
    // header('Cache-Control: max-age=0');
    
    $campaigns = Doctrine_Core::getTable('EmailCampaigns')->createQuery()->execute(array(), Doctrine_Core::HYDRATE_ARRAY);
    echo "\t";
    foreach($campaigns as $key=>$campaign) {
      echo $campaign['short_label'];
      echo "\t\t\t\t\t\t\t\t";
    }
    echo 'total';
    echo "\t\t\t\t\t\t\t\t";
    echo "\n";
    echo 'email'."\t";
    foreach($campaigns as $campaign) {
      echo 'selected'."\t".'hard_bounce'."\t".'soft_bounce'."\t".'received'."\t".'opened'."\t".'clicked'."\t".'unsubscribed'."\t".'complaint'."\t";
    }
    echo 'selected'."\t".'hard_bounce'."\t".'soft_bounce'."\t".'received'."\t".'opened'."\t".'clicked'."\t".'unsubscribed'."\t".'complaint'."\t";
    echo "\n";
    
    $manager = Doctrine_Manager::getInstance();
    $conn = $manager->getCurrentConnection();
    
    $emailsSql = 'SELECT DISTINCT email FROM email_campaign_user_details ecud, contant_information ci WHERE ecud.contant_information_id = ci.id';
    $emailsResult = $conn->execute($emailsSql)->fetchAll(PDO::FETCH_ASSOC);
    
    foreach($emailsResult as $email)
    {
      echo $email['email']."\n";
    }
    die();
  }
  
  
}
